<template>
  <a-menu
    v-model:open-keys="openKeys"
    :selected-keys="selectedKeys"
    :collapsed-width="Theme.siderCollapWidth"
    class="layout-menu"
    accordion
    :theme="theme"
  >
    <template v-for="menu in menuList" :key="menu.path">
      <sider-menu-item :route="menu" />
    </template>
  </a-menu>
</template>

<script setup>
import { reactive, onMounted, watch, toRefs, inject } from 'vue'
import { useRoute } from 'vue-router'
import { Theme } from '@/config'
import SiderMenuItem from './SiderMenuItem.vue'

const props = defineProps({
  theme: {
    type: String,
    default: 'dark'
  },
  menuList: {
    type: Array,
    default: () => []
  }
})

const collapsed = inject('collapsed')
const useRoutes = useRoute()
const state = reactive({
  selectedKeys: [],
  openKeys: [],
  cachedOpenKeys: [],
  rootSubmenuKeys: []
})
const { selectedKeys, openKeys } = toRefs(state)

/**
 * 更新菜单，选中当前页
 */
const updateMenuState = () => {
  const { path, matched, meta } = useRoutes
  const routes = matched.concat()
  const lastPath = routes[routes.length - 1].path
  // 是否存在高亮路由
  const currPath = meta?.highlight ? meta.highlight : path
  let openKey = []
  // 处理父级的展开
  if (lastPath.indexOf('/:') > -1) {
    openKey.push(lastPath.split('/:')[0])
  } else {
    routes.pop()
  }
  routes.forEach((item) => {
    openKey.push(item.path)
  })

  state.selectedKeys = [currPath]
  // 缓存openkeys
  collapsed.value ? (state.cachedOpenKeys = openKey) : (state.openKeys = openKey)
}

/**
 * 监控根菜单
 */
watch(
  () => props.menuList,
  (menus) => {
    state.rootSubmenuKeys = menus.map((i) => i.path) || []
  }
)

/**
 * 监控
 */
watch(collapsed, (val) => {
  if (val) {
    state.cachedOpenKeys = state.openKeys.concat()
    state.openKeys = []
  } else {
    state.openKeys = state.cachedOpenKeys
  }
})

/**
 * 监控路由，更新菜单
 */
watch(useRoutes, () => {
  updateMenuState()
})

onMounted(() => {
  updateMenuState()
})
</script>
